<script setup lang="ts">
import {ref, toRaw, watch} from 'vue'
import {CalculatorRecord} from "./type.ts";
import InputInlineEditor from "./components/InputInlineEditor.vue";
import {cloneDeep, debounce} from "lodash-es";
import {Dialog} from "./lib/dialog.ts";

const containerBox = ref<HTMLElement | null>(null)
const isView = ref(false)
const records = ref<CalculatorRecord[]>([])
let doc: DbDoc | null = null

const autoSetHeight = debounce(() => {
    // @ts-ignore
    const height = containerBox.value?.clientHeight + 1
    window.focusany && window.focusany.view.setHeight((height || 100))
}, 0)

const sync = () => {
    if (!isView.value) {
        let data = cloneDeep(toRaw(records.value))
        data = data.filter(r => {
            // @ts-ignore
            delete r.runtime
            return true
        })
        if (!doc) {
            doc = {
                _id: 'records',
            }
        }
        doc.data = data
        if (window.focusany) {
            const ret = window.focusany.db.put(doc)
            if (!ret.ok) {
                Dialog.tipError('更新失败')
            } else {
                doc._rev = ret.rev
            }
        }
    }
}


watch(records, () => {
    if (!isView.value) {
        if (!records.value.length || records.value[records.value.length - 1].formula) {
            records.value.push({
                formula: '',
                title: '未命名',
                runtime: {
                    textarea: null,
                    result: null
                },
            });
        }
    }
    records.value.forEach((r, index) => {
        try {
            r.runtime.result = eval(r.formula)
        } catch (e) {
            r.runtime.result = '?'
        }
    })
    autoSetHeight()
}, {
    deep: true,
    immediate: true
});

const doEditTitle = (index: number, value: string) => {
    records.value[index].title = value
    sync()
}
const onChange = (index: number, value: string) => {
    if (!isView.value) {
        if ('' == value) {
            records.value.splice(index, 1)
            sync()
        }
    }
}
const doCopy = (index: number) => {
    const record = records.value[index]
    window.focusany && window.focusany.copyText(record.runtime?.result)
    window.focusany && window.focusany.showToast(`已复制 ${record.runtime?.result}`)
}

window.focusany && focusany.onPluginReady((data) => {
    console.log('onPluginReady', data)
    isView.value = data.isView
    // isView.value = true
    if (isView.value) {
        const query = focusany?.getQuery(data.requestId)
        records.value = [
            {
                formula: (query.keywords || query.currentText) as string,
                title: '未命名',
                runtime: {
                    textarea: null,
                    result: null
                },
            }
        ]
    } else {
        doc = focusany.db.get('records')
        if (doc) {
            records.value = (doc.data || []).map((r: any) => {
                return {
                    formula: r.formula,
                    title: r.title,
                    runtime: {
                        textarea: null,
                        result: null
                    },
                }
            })
        }
    }
})
</script>

<template>
    <div class="relative"
         ref="containerBox">
        <div v-for="(r,rIndex) in records" class="pb-2 relative z-10">
            <div class="p-3"
                 :class="isView?'':'rounded-lg bg-white shadow mx-3 mt-3 border border-solid border-gray-100'">
                <div class="formula-container">
                    <a-textarea placeholder="输入公式计算"
                                :ref="el=>(r.runtime.textarea=el)"
                                v-model="r.formula"
                                @change="onChange(rIndex,$event)"
                                auto-size allow-clear/>
                </div>
                <div class="flex items-center h-10">
                    <div class="text-gray-400" v-if="!isView">
                        <InputInlineEditor :value="r.title" @change="doEditTitle(rIndex,$event)">
                            <div class="cursor-pointer ml-2 group">
                                {{ r.title }}
                                <icon-edit class="group-hover:inline-block hidden"/>
                            </div>
                        </InputInlineEditor>
                    </div>
                    <div v-if="null!==r.runtime?.result"
                         :class="isView?'text-lg':'text-2xl'"
                         class="flex-grow text-right text-gray-400 pr-4">
                        =
                    </div>
                    <div class="cursor-pointer"
                         :class="isView?'text-lg':'text-4xl'"
                         @click="doCopy(rIndex)">
                        {{ r.runtime?.result }}
                    </div>
                </div>
            </div>
        </div>
        <div v-if="!isView" class="fixed bottom-5 right-5">
            <img src="./assets/image.svg" class="w-40"/>
        </div>
    </div>
</template>

<style lang="less" scoped>
.formula-container {
    :deep(textarea) {
        font-size: 1rem;
    }
}
</style>
